﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Diagnostics;
using System.IO;
using Tornado.Properties;

namespace Tornado
{
    public partial class frmReceiveFile : Form
    {
        const int MaxLen = 256;
        volatile private IPAddress addr;
        volatile private int port;
        volatile private bool open;

        public frmReceiveFile(IPAddress addr, int port, bool open)
        {
            InitializeComponent();
            this.addr = addr;
            this.port = port;
            this.open = open;
            Config.load();

        }

        private void frmReceiveFile_Load(object sender, EventArgs e)
        {
            this.Top = Screen.PrimaryScreen.WorkingArea.Bottom - this.Height;
            this.Left = Screen.PrimaryScreen.WorkingArea.Right - this.Width;
        }

        private void frmReceiveFile_Shown(object sender, EventArgs e)
        {
            bgReceiveFile.RunWorkerAsync();
        }

        private void bgReceiveFile_DoWork(object sender, DoWorkEventArgs e)
        {
            TcpClient c = new TcpClient();
            try
            {
                c.Connect(addr, port);
                if (c.Connected)
                {
                    NetworkStream stream = c.GetStream();

                    int sizeOfName = getSize(stream);
                    byte[] b = new byte[sizeOfName];
                    int readed = 0;
                    while (readed < sizeOfName)
                    {
                        readed += stream.Read(b, readed, sizeOfName - readed);
                    }
                    string fileName = Encoding.UTF8.GetString(b);
                    bgReceiveFile.ReportProgress(0, fileName);

                    int sizeOfData = getSize(stream);

                    fileName = DateTime.Now.ToString("[yyyy-MM-dd hh-mm-ss] ") + fileName;
                    string filePath = Application.StartupPath;

                    filePath = Path.Combine(filePath, fileName);
                    try
                    {
                        b = new byte[MaxLen];
                        FileStream fStream = File.Create(filePath);
                        readed = 0;
                        int readSize;
                        int curProg = 0;
                        while (readed < sizeOfData)
                        {
                            readSize = stream.Read(b, 0, MaxLen);
                            fStream.Write(b, 0, readSize);
                            readed += readSize;
                            int prog = (int)((float)readed / sizeOfData * 100);
                            if (prog > curProg)
                            {
                                curProg = prog;
                                bgReceiveFile.ReportProgress(curProg);
                            }
                        }
                        if (open)
                            e.Result = filePath;
                    }
                    catch { }
                }
                c.Close();
            }
            catch { }
        }

        int getSize(NetworkStream s)
        {
            int sizeInt = sizeof(int);
            byte[] b = new byte[sizeInt];
            int readed = 0;

            while (readed < sizeInt)
            {
                readed += s.Read(b, readed, sizeInt - readed);
            }
            int r = b[0] * (1 << 24) + b[1] * (1 << 16) + b[2] * (1 << 8) + b[3];
            return r;
        }

        private void bgReceiveFile_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            if (e.ProgressPercentage == 0)
            {
                string fileName = (string)e.UserState;
                this.Text = fileName;
            }
            progressReceive.Value = e.ProgressPercentage;
        }

        private void bgReceiveFile_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (open)
            {
                try
                {
                    string filePath = (string)e.Result;
                    Process.Start(filePath);
                }
                catch { }
            }
            this.Close();
        }
    }
}
